<?php

namespace app\admin\controller;

use app\common\controller\AdminBase;
use think\App;
use think\exception\ValidateException;

/**
 * Qustiontype控制器
 */
class Qustiontype extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Qustiontype();

        $this->validate = \app\admin\validate\Qustiontype::class;
    }

    /**
     * 列表
     */
    public function index()
    {
        list($limit, $where, $sortArr) = $this->buildTableParames();
        $list = $this->model
            ->where($where)
            ->order('sort asc')
            ->paginate($limit);
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => $list->total(),
            'data' => $list->items(),
        ];
        return json($data);
    }

    public function add()
    {
        $post = $this->request->post();
        try {
            $questiontype = table('qustiontype')->where(['title' => $post['title']])->find();
            if (!empty($questiontype)) {
                return error('请勿重复添加问题分类');
            }
            $result = $this->model->save($post);
            if ($result) {
                return success('添加成功！');
            }
            return error('添加失败');
        } catch (ValidateException $e) {

            return error($e->getError());
        } catch (\Exception $e) {
            return error('添加失败:' . $e->getMessage());
        }
    }
}
